<?php
class Dbschema_model extends Common_model {
	
    public function __construct(){
        parent::__construct();
    }
    
    /**
     * 修改
     * @param Array $schema_config
     */
    public function modify($schema_name,$schema_config){
        
        $arr_table_col = $this->get_cols($schema_name);
        $arr_schema_col = array();
        
        //更新列
        if(!empty($schema_config['columns'])){
            foreach ($schema_config['columns'] as $k=>$v){

                $sql = '';
                $alter_header = '';
                if(in_array($k, $arr_table_col)){
                   $alter_header = "ALTER TABLE `".$schema_name."` CHANGE `".$k."` `".$k."` ";
                }else{
                   $alter_header = "ALTER TABLE `".$schema_name."` ADD `".$k."` ";
                }
                
                $type = '';
                if($v['type'] == 'number' || $v['type'] == 'time'){
                    $type = 'INT(11)';
                }elseif($v['type'] == 'bool'){
                    $type = 'TINYINT(1)';
                }else{
                    $type = $v['type'];
                }
                
                $not_null = 'NULL';
                if(!empty($v['required']) && $v['required'] === true){
                    $not_null = 'NOT NULL';
                }
                
                $extra = '';
                if(!empty($v['extra'])){
                    $extra = $v['extra'];
                    $pk = "PRIMARY KEY (`".$k."`)";
                }
                
                $default = '';
                if(!empty($v['default'])){
                    if($v['type'] == 'bool'){
                        $default = $v['default'] === true ? '1' : '0';
                    }
                    $default = $v['default'];
                }
                
                $default = empty($default) ? '' : "DEFAULT '".$default."'";
                
                $comment = empty($v['label']) ? '' : 'COMMENT \''.$v['label'].'\'';  
                                  
                $sql = $alter_header.$type." ".$not_null." ".$default." ".$comment.";";
                
                $arr_schema_col[] = $k;
                $this->query($sql);
                
            }
            
        }
        
        //删除原表中的列
        foreach ($arr_table_col as $k=>$v){
            if(in_array($v, $arr_schema_col)) continue;
            $sql = '';
            $sql = "ALTER TABLE `".$schema_name."` DROP `".$v."`";
            $this->query($sql);
        }
        
        return true;
                
    }
    
    
}

